package com.example.demo.config

import org.springframework.context.annotation.Configuration
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor

import org.hibernate.validator.HibernateValidator
import org.springframework.context.annotation.Bean
import javax.validation.Validation
import javax.validation.Validator

import javax.validation.ValidatorFactory




@Configuration
class ValidatorConfig {

    fun validator(): Validator? {
        val validatorFactory: ValidatorFactory = Validation.byProvider(HibernateValidator::class.java)
                .configure() //failFast的意思只要出现校验失败的情况，就立即结束校验，不再进行后续的校验。
                .failFast(true)
                .buildValidatorFactory()
        return validatorFactory.validator
    }

    @Bean
    fun methodValidationPostProcessor(): MethodValidationPostProcessor? {
        val methodValidationPostProcessor = MethodValidationPostProcessor()
        validator()?.let { methodValidationPostProcessor.setValidator(it) }
        return methodValidationPostProcessor
    }

}